package com.yan.qing.demo;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * @description: 组合执行代码
 * @author: lf
 * @create: 2021年12月16日 10:46:00
 */
@Service
public class ZuheTest {
    CompletableFuture<String> findAccount(String accountId) {
        return CompletableFuture.supplyAsync(() -> {
            // mock finding account from database
            return "account+" + accountId;
        });
    }
    public void batchProcess(List<String> accountIdList) {
        // 并行根据accountId查找对应account
        List<CompletableFuture<String>> accountFindingFutureList =
                accountIdList.stream().map(accountId -> findAccount(accountId)).collect(Collectors.toList());

        // 使用allOf方法来表示所有的并行任务

        CompletableFuture<Void> allFutures = CompletableFuture
                .allOf (accountFindingFutureList.toArray (new CompletableFuture[accountFindingFutureList.size ()]));
        // .anyOf (accountFindingFutureList.toArray (new CompletableFuture[accountFindingFutureList.size ()]));

        // 下面的方法可以帮助我们获得所有子任务的处理结果
        CompletableFuture<List<String>> finalResults = allFutures.thenApply(v -> {
            return accountFindingFutureList.stream().map(accountFindingFuture -> accountFindingFuture.join())
                    .collect(Collectors.toList());
        });
        finalResults.getNow (accountIdList).forEach (System.out ::println);
    }
}